<?php
namespace App\Modules\Relationship\Services;


use App\Http\Model\Hint;
use App\Http\Model\RoomUser;
use Illuminate\Support\Facades\DB;
use App\Http\Model\Medal;
use App\Http\Model\UserProp;
use App\Http\Model\Room;
use App\Http\Model\User;

class FriendsService extends RsCommonService {

    const INTIMACY_LIMIT = 1000;
    private $modelRoomUser;
    private $modelMedal;
    private $userPropModel;
    private $modelRoom;
    private $modelUser;
    public function __construct(){
        parent::__construct();
        $this->modelRoomUser = new RoomUser();
        $this->modelMedal = new Medal();
        $this->userPropModel = new UserProp();
        $this->modelRoom = new Room();
        $this->modelUser = new User;
    }
    //获取用户列表
    public function getFriendList($userId, $pageIndex = 0, $pageSize = 10): array
    {
        return $this->formatFriendList($userId, $pageIndex, $pageSize);
    }

    //获取用户列表
    private function formatFriendList($userId, $pageIndex = 0, $pageSize = 10, $haveRs = 0): array {
        $data = [];
        $rows = $this->rsModel->getList($userId, $pageIndex * $pageSize, $pageSize, $haveRs);
        $cou = $this->rsModel->getListCount($userId, $haveRs);
        $levels = $this->rsRelationshipLevelModel->getAllLevel();
        if (count($rows) > 0) {
            // 获取全部uid
            $friendIds = array_column($rows, 'friendId');
            $friends = $this->user->get_users_by_ids($friendIds);
            $idxIdFriends = array_column($friends, null, 'user_id');
            $medalArr = $this->modelMedal->getMedalUserListCache($friendIds, false);
            $medalData = [];
            foreach ($medalArr as $val){
                if(empty($val)){
                    continue;
                }
                $medalData[$val[0]['user_id']] = $val;
            }
            $continueRow = [];
            foreach ($rows as $row) {
                $f = $idxIdFriends[$row->friendId];
                if ($f != null) {
                    try {
                        $rsInfo = $this->getOneRelationshipInfoByType($row->type, $userId, $row->friendId);
                    } catch (\Exception $e) {
                        if ($row->type ==1){
                            DB::table('rs_relationship')->where(['user_id' => $userId, 'friend_id'=>$row->friendId,'is_deleted'=>0,'type'=>1])->update(['is_deleted'=>1]);
                            DB::table('rs_relationship')->where(['friend_id' => $userId, 'user_id'=>$row->friendId,'is_deleted'=>0,'type'=>1])->update(['is_deleted'=>1]);
                        }
                        $continueRow[] = ['user_id' => $userId, 'friend_id'=>$row->friendId, 'type'=>$row->type];
                        continue;
                    }

                    $curLevel = $this->rsRelationshipLevelModel->getLevelByIntimate($rsInfo['intimate'], $row->type);
                    // 获取
                    $levelIdkey = $row->type . '_' . $curLevel['level'];
                    if (!$levels[$levelIdkey]){
                        $continueRow[] = ['user_id' => $userId, 'friend_id'=>$row->friendId, 'levelIdkey'=>$levelIdkey];
                        continue;
                    }
                    $dataItem = [];
                    $dataItem['id'] = $row->id;
                    $dataItem['userId'] = $f['user_id'];
                    $dataItem['userUid'] = $f['user_uid'];
                    $dataItem['nickname'] = $f['nickname'];
                    $dataItem['gender'] = $f['gender'];
                    $dataItem['sign'] = $f['sign'];
                    $dataItem['adapt_images'] = $f['adapt_images'][0];
                    $dataItem['images'] = $f['images'][0];
                    $dataItem['thumbnails'] = $f['thumbnails'][0];
                    $dataItem['type'] = $row->type;

                    $dataItem['levelName'] = $levels[$levelIdkey]['levelName'];
                    $dataItem['levelImg'] = $this->imageUrl($levels[$levelIdkey]['levelImg']);
                    $dataItem['intimate'] = $rsInfo['intimate'];
                    $dataItem['isRoom'] = 0;
                    $dataItem['roomId'] = 0;
                    if (array_key_exists(intval($f['user_id']), $medalData)){
                        $dataItem['medal'] = $medalData[intval($f['user_id'])];
                    }
                    else{
                        $dataItem['medal'] = [];
                    }

                    $dataItem['modelStr'] = "";
                    //获取用户是否在直播间 update:sn
                    $userCurRoom = $this->modelRoomUser->get_user_cur_room($f['user_id']);
                    //查询用户是否使用防跟随道具
                    $propUseInfo = $this->userPropModel->getPropUseTime($f['user_id'], 19);
                    if (!$propUseInfo) {
                        $dataItem['isRoom'] = $userCurRoom ? 1 : 0;
                        $dataItem['roomId'] = $userCurRoom ? intval($userCurRoom) : 0;
                        if($userCurRoom){
                            $roomIds[] = $userCurRoom;
                        }
                    }
                    $dataItem['remarkName'] = $this->modelUser->getUserRemark($userId, $f['user_id']);
                    $data[] = $dataItem;
                }
            }
            // write_log(
            //     'RsCommonService'.(isCli()?'-cli':''),
            //     '[INFO] 好友关系-formatFriendList',
            //     ['userId'=>$userId, 'continueRow'=>$continueRow]
            // );
        }

        $dataList =  array_values($data);
        //判断用户是否在房间 update:sn
        if(isset($roomIds)){
            $roomData = $this->modelRoom->get_rooms_by_ids($roomIds);
            foreach ($dataList as $k=>$v){
                if(!empty($v['roomId'])){
                    $roomId = $v['roomId'];
                    $filterRoomData = array_values(array_filter($roomData, function ($param) use ($roomId) {
                        return $roomId == $param['roomId'];
                    }));
                    $dataList[$k]['modelStr'] = $filterRoomData && $filterRoomData[0] && isset($filterRoomData[0]['model_str']) ? $filterRoomData[0]['model_str'] : "";
                }
            }
        }
        $return = [];
        $return['list'] = array_values($dataList);
        $return['pageIndex'] = $pageIndex;
        $return['pageCount'] = ceil($cou/$pageSize);
        $return['pageSize'] = intval($pageSize);
        return $return;
    }

    public function getRelationship ($userInfo, $friendId) {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        try {
            $return = array();
            $rsRecord = $this->rsModel->getOneRelation($userInfo['user_id'], $friendId);
            // 未互相关注
            if (count($rsRecord) == 0) {
                return array('type' => -1);
            }
            $friend = $this->getOneRelationshipInfoByType($rsRecord['type'], $userInfo['user_id'], $friendId);
            $levelInfo = $this->getOneLevel($rsRecord['type'], $friend['level']);
            $return = array(
                "type" => $rsRecord['type'],
                "intimacy" => $friend['intimate'],
                "level" => $friend['level'],
                "levelName" => $levelInfo['levelName'],
                "levelImg" => $this->imageUrl($levelInfo['levelImg']),
                "backgroudImg" => $this->imageUrl($levelInfo['levelImg'])
            );
            return $return;
        } catch (\Exception $e) {
            $code = Hint::ERR_SYS_FAIL;
            $msg = Hint::getErrCodeMsg($code);
            $data['error_msg'] = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
        }
        return compact('code', 'msg', 'data');
    }

    public function reportChatNum($userId , $friendId, $num=1) {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {

        } while (false);
        return compact('code', 'msg', 'data');
    }

    private function imageUrl ($file) {
        if (!empty($file)) {
            return getPicDomain() . $file;
        }
        return '';
    }

}